/* Copyright (c) 2010-2020 Vadim Surov.
 */

package com.srv.server;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

import com.srv.shared.LoginInfo;
import com.srv.shared.Service;
import com.srv.shared.SetInfo;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.sencha.gxt.data.shared.SortInfo;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoadResultBean;

/**
 * The server-side RPC endpoint for {@link Service}.
 *
 *
 */
@SuppressWarnings("serial")
public class ServiceImpl extends RemoteServiceServlet implements Service {


	/**
	 * A reference to the data store.
	 */
	private static final Store store  = StoreSingleton.getInstance();

	/**
	 * A reference to a cache service.
	 */
	private final Cache cache = new Cache(MemcacheServiceFactory
			.getMemcacheService());	

	/**
	 * A convenient way to get the current user and throw an exception if the user
	 * isn't logged in.
	 *
	 * @param userService
	 *          the user service to use
	 * @return the current user
	 * @throws AccessDeniedException
	 */
	private static User tryGetCurrentUser(UserService userService)
			throws AccessDeniedException {
		if (!userService.isUserLoggedIn()) {
			throw new Service.AccessDeniedException();
		}
		return userService.getCurrentUser();
	}

	public LoginInfo login(String sessionKey, String runKey) 
			throws AccessDeniedException {
		final UserService userService = UserServiceFactory.getUserService();
		final User user = tryGetCurrentUser(userService);

		String redirectUrl;
		String baseUrl;

		if (getThreadLocalRequest().getLocalPort() != 8888)	{
			baseUrl = "http://one-or-two.appspot.com";
			redirectUrl = baseUrl + "/Oneortwo.html"; 
		} else {
			baseUrl = "http://127.0.0.1:8888";
			redirectUrl = baseUrl + "/Oneortwo.html?gwt.codesvr=127.0.0.1:9997";    	
		}

		redirectUrl += ((sessionKey==null)?"":("&session=" + sessionKey));
		redirectUrl += ((runKey==null)    ?"":("&run=" + runKey));

		final LoginInfo loginInfo = new LoginInfo();

		if (user != null) {
			loginInfo.setLoggedIn(true);
			loginInfo.setEmail(user.getEmail());
			loginInfo.setNickname(user.getNickname());
			loginInfo.setBaseUrl(userService.createLoginURL(baseUrl));
			loginInfo.setLogoutUrl(userService.createLogoutURL(userService.createLoginURL(redirectUrl)));
		} else {
			loginInfo.setLoggedIn(false);
			loginInfo.setBaseUrl(userService.createLoginURL(baseUrl));
		}
		return loginInfo;
	}


	public PagingLoadResult<SetInfo> getSetInfoList(PagingLoadConfig config) {

		ArrayList<SetInfo> posts = new ArrayList<SetInfo>();
		for (int i = 0; i < 50; i++)
			posts.add(new SetInfo("keyword" + i, "name" + i, "email" + i, "tag1, tag2", "<table border=1><tr><td><i>htm sdfsdf sdfsdf sdfsdf sdfsdfl</i></td></tr></table>", new Date()));


		if (config.getSortInfo().size() > 0) {
			SortInfo sort = config.getSortInfo().get(0);
			if (sort.getSortField() != null) {
				final String sortField = sort.getSortField();
				if (sortField != null) {
					Collections.sort(posts, sort.getSortDir().comparator(new Comparator<SetInfo>() {
						public int compare(SetInfo p1, SetInfo p2) {
							if (sortField.equals("keyword")) {
								return p1.getKeyword().compareTo(p2.getKeyword());
							} else if (sortField.equals("ownerName")) {
									return p1.getAuthorName().compareTo(p2.getAuthorName());
							} else if (sortField.equals("tags")) {
								return p1.getFirstCardHtml().compareTo(p2.getFirstCardHtml());
							} else if (sortField.equals("date")) {
								return p1.getDate().compareTo(p2.getDate());
							}
							return 0;
						}
					}));
				}
			}
		}		

		ArrayList<SetInfo> sublist = new ArrayList<SetInfo>();
		int start = config.getOffset();
		int limit = posts.size();
		if (config.getLimit() > 0) {
			limit = Math.min(start + config.getLimit(), limit);
		}
		for (int i = config.getOffset(); i < limit; i++) {
			sublist.add(posts.get(i));
		}
		return new PagingLoadResultBean<SetInfo>(sublist, posts.size(), config.getOffset());	
	}	

}
